import '../../util/_base_export.dart';
import '../../util/_view_export.dart';

import '../../blocs/code.dart';
import '../../blocs/cart.dart';
import '../../util/app_util.dart';

class AccountVouchersListScreen extends StatefulWidget {
  final String scenario;
  const AccountVouchersListScreen(
    this.scenario, {
    Key? key,
  }) : super(key: key);
  @override
  _AccountVouchersListScreenState createState() => _AccountVouchersListScreenState();
}

class _AccountVouchersListScreenState extends State<AccountVouchersListScreen> {
  _loadVoucher() async {
    AppSession.appUtil.loadVouchers({});
  }

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance?.addPostFrameCallback((callback) {
      _loadVoucher();
    });
  }

  List<Widget> list = List<Widget>.empty(growable :true);

  @override
  Widget build(BuildContext context) {
    CartBloc _cart = Provider.of<CartBloc>(context, listen: false);

    return Scaffold(
      appBar: AppBar(
        brightness: Brightness.light,
        leading: GestureDetector(
          behavior: HitTestBehavior.opaque,
          onTap: () {
            Navigator.pop(context);
          },
          child: Container(
            child: Icon(
              Icons.chevron_left,
              color: AppColor.blackMain,
              size: 32,
            ),
          ),
        ),
        title: Text(
          AppText.text['account_voucher_name'],
          style: TextStyle(color: AppColor.blackMain),
        ),
        // actions: <Widget>[
        //   GestureDetector(
        //                     onTap: () {
        //                       if ((AppSession.authortoken ?? '').isEmpty)
        //                         AppPopupService.showAlertSimple(
        //                           'I',
        //                           '请先登录',
        //                           '',
        //                           iv_cancel_text: '先不了',
        //                           cancel: _cancel,
        //                           iv_confirm_text: '去登录',
        //                           confirm: _login,
        //                         );
        //                       else {
        //                         App.router.navigateTo(context, AppRoutes.accountRedeem);
        //                       }
        //                     },
        //                     child: Row(
        //                       children: <Widget>[

        //   Icon(Icons.perm_device_information),
        //   ]),
        // ],
      ),
      body: SingleChildScrollView(
        child: Container(
          color: Colors.grey[50],
          margin: EdgeInsets.only(top: 20.h),
          child: _voucherList(context, _cart),
        ),
      ),
    );
  }

  Widget _voucherList(BuildContext context, CartBloc ib_cart) {
    list.clear();
    for (var lv_voucher in AppSession.appUtil.vouchers) {
      list.add(GestureDetector(
        onTap: () async {},
        behavior: HitTestBehavior.opaque,
        child: _voucherBlock(lv_voucher, ib_cart),
      ));
    }
    if (list.isEmpty)
      return Center(
        child: Column(
          children: <Widget>[
            Image.asset('assets/account/voucher_empty.png'),
            Text(AppText.text['account_voucher_novoucher'] ?? ''),
          ],
        ),
      );
    else
      return Column(children: list);
  }

  Widget _voucherBlock(Map iv_voucher, CartBloc ib_cart) {
    var _voucher_bg;
    switch (iv_voucher['voucher_type_id']) {
      case 1:
        _voucher_bg = 'assets/coupon/voucher_bg_yellow.png';
        break;
      case 2:
        _voucher_bg = 'assets/coupon/voucher_bg_red.png';
        break;
      default:
        _voucher_bg = 'assets/coupon/voucher_bg_yellow.png';
    }

    var _additiona_widget;
    var _widget_flag = false;
    if (widget.scenario == 'ORDER') {
      _additiona_widget = FlatButton(
        child: Container(
          width: 100.w,
          height: 30.h,
          decoration: AppDecoration.buttonOne,
          child: Center(child: Text('使用')),
        ),
        onPressed: () async {
          Map<String, dynamic> lm_param = {};
          lm_param = {
            'voucher_code': iv_voucher['access_code'],
          };
          var lv_result = await ib_cart.checkoutUpdate(lm_param);
          if (lv_result) Navigator.pop(context);
        },
      );
      _widget_flag = true;
    } else if (iv_voucher['voucher_type_id'] == 2) {
      //TODO
      // _additiona_widget = GestureDetector(
      //   behavior: HitTestBehavior.opaque,
      //   onTap: () {
      //     App.router.navigateTo(context, AppRoutes.accountVoucherUsage);
      //   },
      //   child: AppTextService.simpleText(
      //     '点击查看详情 > ',
      //     iv_color: AppColor.redMain,
      //     iv_size: 12,
      //   ),
      // );
      // _widget_flag = true;
    }
    return Padding(
      padding: EdgeInsets.symmetric(horizontal: 18.w),
      child: Card(
        child: Container(
          // margin: EdgeInsets.symmetric(horizontal: 10.w),

          width: ScreenUtil().screenWidth.toDouble(),
          child: Row(
            children: <Widget>[
              // ((iv_voucher['image_url'] ?? '').isNotEmpty)
              //     ? CachedNetworkImage(
              //         imageUrl: iv_voucher['image_url'],
              //         fit: BoxFit.cover,
              //       )
              //     : Image.asset('assets/coupon/voucher_bg_yellow.png'),
              Container(
                height: 128.h,
                width: 130.w,
                child: Center(
                    child: Text(
                  '\$${iv_voucher['balance']}',
                  style: AppTextStyle.balanceVoucherList,
                )),
                decoration: BoxDecoration(
                  color: Colors.grey[50],
                  borderRadius: BorderRadius.only(
                      topLeft: Radius.circular(20.0), bottomLeft: Radius.circular(20.0)),
                  image: DecorationImage(
                    image: AssetImage(_voucher_bg),
                    fit: BoxFit.cover,
                  ),
                ),
              ),
              Container(
                height: 128.h,
                width: 160.w,
                color: Colors.white,
                padding: EdgeInsets.symmetric(horizontal: 15.w),
                // margin: EdgeInsets.symmetric(horizontal: 10.w),
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: <Widget>[
                    AppTextService.simpleText(
                        iv_voucher['name'] ?? '' + ' 余额 \$${iv_voucher['balance']}',
                        iv_color: AppColor.blackMain,
                        iv_size: 14),
                    Text(
                      '备注: ' + iv_voucher['desc'],
                      overflow: TextOverflow.ellipsis,
                      style: TextStyle(
                        color: AppColor.greyText,
                        fontSize: 12.sp,
                      ),
                      maxLines: 2,
                      softWrap: true,
                    ),
                    if (_widget_flag) _additiona_widget,
                  ],
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}
